<template>
    <div>
        <el-form :model="param" inline style="text-align: left; position: relative;">
          <el-form-item label="选择月份">
            <el-date-picker
              v-model="param.date"
              type="month"
              placeholder="选择月份"
              value-format="yyyy-MM"
              @change="handleMonthChange"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="param.ename" placeholder="请输入姓名" clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-radio-group v-model="dataType" @change="getTableDate">
              <el-radio :label="0">工作量</el-radio>
              <el-radio :label="1">加班时间</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
  
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          height="450px"
          :key="tableKey"
          :header-cell-class-name="headerCellClassName"
        >
          <el-table-column
            prop="ename"
            label="姓名"
            fixed
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            v-for="day in daysWithWeek"
            :key="day.date"
            :prop="'day' + day.date"
            width="43"
            align="center"
          >
            <template slot="header">
              <div class="header-container">
                <div class="header-line">{{ day.date }}</div>
                <div class="header-line week-header">{{ day.weekDay }}</div>
              </div>
            </template>
            <template slot-scope="scope">
              <el-input
                v-model="scope.row['day' + day.date]"
                size="mini"
                @change="handleEdit()"
              ></el-input>
            </template>
          </el-table-column>
          <!-- 合计列 -->
          <el-table-column
            label="合计"
            fixed="right"
            width="60"
            align="center"
          >
            <template slot-scope="scope">
              {{ calculateSum(scope.row) }}
            </template>
          </el-table-column>
        </el-table>
  
        <el-pagination
          style="margin-top: 20px; text-align: right;"
          :current-page="parseInt(param.page)"
          :page-size="parseInt(param.limit)"
          :page-sizes="[6,10,15,20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
    </div>
  </template>
  
  <script>
  export default {
    name: 'monthView',
    data() {
      return {
        daysWithWeek: [],
        tableData: [],
        loading: false,
        tableKey: 0,
        total: 0,
        dataType: 0,
        lostDates: [],
        param: {
          date: this.getCurrentMonth(),
          ename: '',
          page: '1',
          limit: '6',
          deptno: 1
        }
      }
    },
    methods: {
      // 获取当前月份（格式：yyyy-MM）
      getCurrentMonth() {
        const now = new Date()
        const year = now.getFullYear()
        const month = (now.getMonth() + 1).toString().padStart(2, '0')
        return `${year}-${month}`
      },
      
      // 月份变化处理
      handleMonthChange() {
        this.updateTableHeaders()
        this.getTableDate()
      },
              
      // 根据选择的月份更新表头
      updateTableHeaders() {
        if (!this.param.date) return
        
        this.loading = true
        
        setTimeout(() => {
          const [year, month] = this.param.date.split('-').map(Number)
          const daysInMonth = new Date(year, month, 0).getDate()
          
          // 生成包含日期和星期的对象数组
          this.daysWithWeek = Array.from({length: daysInMonth}, (_, i) => {
            const date = i + 1
            const weekDay = this.getWeekDay(year, month - 1, date)
            return {
              date: date,
              weekDay: weekDay
            }
          })
          
          this.tableKey += 1
          this.loading = false
        }, 500)
      },
  
      // 获取星期几
      getWeekDay(year, month, date) {
        const day = new Date(year, month, date).getDay()
        const weekDays = ['日', '一', '二', '三', '四', '五', '六']
        return weekDays[day]
      },
  
      // 计算每行数据的和
      calculateSum(row) {
        let sum = 0
        this.daysWithWeek.forEach(day => {
          const value = parseFloat(row['day' + day.date]) || 0
          sum += value
        })
        return sum.toFixed(2)
      },
  
      // 处理单元格编辑
      handleEdit() {
        this.$forceUpdate()
      },

      getLostDate() {
        this.$http.post('/getLostDateByDept',{
          page: 1,
          limit: 1000,
          deptno: localStorage.getItem('deptno')
        }).then(res => {
          this.lostDates = res.data.data
        }).catch(() => {
          this.$message.error("获取日期失败")
        })
      },
  
      processZeroValues(data) {
        return data.map(row => {
          const processedRow = { ...row };
          
          Object.keys(processedRow).forEach(key => {
            if (key.startsWith('day') && (processedRow[key] === 0 || processedRow[key] === '0')) {
              // 查找匹配的漏报记录
              const matchedLostRecord = this.lostDates.find(item => 
                item.empno === processedRow.empno && 
                this.param.date === item.reportDate.substring(0, 7) && 
                parseInt(item.reportDate.split('-')[2]) === parseInt(key.slice(3))
              );
              
              // 如果有匹配的记录，设置为'漏'，否则清空
              processedRow[key] = matchedLostRecord ? '漏' : '';
            }
          });
          
          return processedRow;
        });
      },
  
      // 表头单元格类名
      headerCellClassName({ column, columnIndex }) {
        return 'custom-header-cell'
      },
  
      getTableDate(){
        this.loading = true
        let url = "/getWorkloadByMonth"
        if (this.dataType === 1) {
          url = "/getOvertimeByMonth"
        }

        this.$http.post(url, this.param).then(res => {
          let tableData = res.data.data || []
          this.total = res.data.count || tableData.length
          
          // 处理0值显示
          this.tableData = this.processZeroValues(tableData)
          
          // 确保每个员工都有所有日期的字段
          this.tableData.forEach(row => {
            this.daysWithWeek.forEach(day => {
              const fieldName = 'day' + day.date
              if (!row.hasOwnProperty(fieldName)) {
                this.$set(row, fieldName, '')
              }
            })
          })
          
          this.loading = false
        }).catch(() => {
          this.$message.error("获取数据失败")
          this.loading = false
        })
      },

      handleSearch() {
        this.param.page = '1'
        this.getTableDate()
      },
  
      handleReset() {
        this.param = {
          date: this.getCurrentMonth(),
          ename: '',
          page: '1',
          limit: '6',
          deptno: localStorage.getItem('deptno')
        }
        this.updateTableHeaders()
        this.getTableDate()
      },
  
      handleSizeChange(val) {
        this.param.limit = val.toString()
        this.getTableDate()
      },
  
      handleCurrentChange(val) {
        this.param.page = val.toString()
        this.getTableDate()
      }
    },
    mounted() {
      this.param.deptno = localStorage.getItem('deptno')
      this.getLostDate()
      this.updateTableHeaders()
      this.getTableDate()
    }
  }
  </script>
  
  <style>
  /* 调整输入框样式 */
  .el-table .el-input__inner {
    border: none;
    text-align: center;
    padding: 0 5px;
  }
  
  .el-table .el-input__inner:focus {
    border: 1px solid #409EFF;
  }
  </style>